package com.kzj.common.interceptor;

import com.kzj.common.FailMsgConstant;
import com.kzj.common.GlobalConstant;
import com.kzj.myJar.common.exception.BaseException;
import com.kzj.myJar.common.utils.InheritableThreadLocalUtil;
import com.kzj.myJar.common.utils.StringUtil;
import com.kzj.myJar.springboot.common.util.JwtUtil;
import com.kzj.myJar.springboot.redis.RedisJsonUtil;
import io.jsonwebtoken.lang.Assert;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Value("${app.jwt.secret}")
    public String jwtSecret;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(GlobalConstant.JWT_HEADER_NAME);
        if(StringUtil.isBlank(token))
            throw new BaseException(FailMsgConstant.TOKEN_IS_NULL);
        Assert.isTrue(RedisJsonUtil.exists(GlobalConstant.TOKEN_KEY_PREFIX+token),FailMsgConstant.TOKEN_NOT_EXISTS);
        Map<String, Object> claims = JwtUtil.parseJwt(token, jwtSecret);
        int userId = (int)claims.get(GlobalConstant.USER_ID);
        InheritableThreadLocalUtil.set(GlobalConstant.USER_ID,userId);
        RedisJsonUtil.set(GlobalConstant.TOKEN_KEY_PREFIX+token,"",GlobalConstant.JWT_VALID_TTL, TimeUnit.MINUTES);
        return true;
    }
}
